package com.yuan.yblog.portal.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuan.yblog.common.exception.Asserts;
import com.yuan.yblog.common.service.EntityCacheService;
import com.yuan.yblog.crud.entity.Comment;
import com.yuan.yblog.crud.entity.Post;
import com.yuan.yblog.crud.entity.User;
import com.yuan.yblog.crud.service.ICommentService;
import com.yuan.yblog.crud.service.IPostService;
import com.yuan.yblog.crud.service.IUserService;
import com.yuan.yblog.portal.dao.mapper.CommentDao;
import com.yuan.yblog.portal.pojo.VO.CommentVO;
import com.yuan.yblog.portal.pojo.contants.Status;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * @author 13527
 * @createDate 2023-12-03 14:18:01
 */
@Service
public class CommentService {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    IUserService iUserService;

    @Autowired
    ICommentService iCommentService;

    @Autowired
    IPostService iPostService;

    @Autowired
    CommentDao commentDao;

    @Autowired
    EntityCacheService entityCacheService;


    /**
     * 根据文章id，分页查询评论
     */
    public IPage<CommentVO> listByPostId(Long postId, Long pageNumber, Long pageSize, String sortKey, Boolean isDesc) {
        if (!iPostService.exists(new QueryWrapper<Post>().eq("id", postId))) {
            Asserts.fail("文章不存在");
        }
        return list(postId, null, pageNumber, pageSize, sortKey, isDesc);

    }

    /**
     * 根据用户id，分页查询评论
     */
    public IPage<CommentVO> listByUserId(Long userId, Long pageNumber, Long pageSize, String sortKey, Boolean isDesc) {
        if (!iUserService.exists(new QueryWrapper<User>().eq("id", userId))) {
            Asserts.fail("用户不存在");
        }
        return list(null, userId, pageNumber, pageSize, sortKey, isDesc);
    }


    /**
     * 分页查询评论
     * @param postId 文章id
     * @param userId 用户id
     * @param pageNumber 页码
     * @param pageSize 页大小
     * @param sortKey 排序字段
     * @param isDesc 是否降序
     */
    private IPage<CommentVO> list(Long postId, Long userId, Long pageNumber, Long pageSize, String sortKey, Boolean isDesc) {
        // 查询
        List<Comment> list = commentDao.list(postId,
                userId,
                (pageNumber - 1) * pageSize,
                pageSize,
                sortKey,
                isDesc);

        Long total = commentDao.countByPostIdOrUserId(postId, userId);
        // 转化
        List<CommentVO> data = new ArrayList<>();
        for (Comment comment : list) {
            // passiveContent：被回复对象的内容
            String passiveContent = "";
            if (comment.getParentId() != null) {
                // 父级评论存在，选择评论的内容
                passiveContent = iCommentService.selectByIdAndBuildCache(comment.getParentId()).getContent();
            } else {
                // 父级评论不存在，选择文章标题
                passiveContent = iPostService.selectByIdAndBuildCache(comment.getPostId()).getTitle();
            }
            CommentVO commentVO = CommentVO.getCommentVO(comment, passiveContent);
            // 获取评论者昵称、头像
            User user = iUserService.selectByIdAndBuildCache(commentVO.getUserId());
            commentVO.setUsername(user.getUsername());
            commentVO.setUserAvatar(user.getAvatar());
            // 收集
            data.add(commentVO);
        }
        // 封装后返回
        IPage<CommentVO> result = new Page<>(pageNumber, pageSize, total);
        result.setRecords(data);
        return result;
    }



    /**
     * 根据评论id，查询评论
     */
    public CommentVO selectOne(Long id) {
        Comment comment = iCommentService.selectByIdAndBuildCache(id);
        if (comment == null) {
            Asserts.fail("评论不存在");
        }
        CommentVO commentVO = CommentVO.getCommentVO(comment, null);
        // 获取评论者昵称、头像
        User user = iUserService.selectByIdAndBuildCache(commentVO.getUserId());

        commentVO.setUsername(user.getUsername());
        commentVO.setUserAvatar(user.getAvatar());
        // 返回结果
        return commentVO;
    }

    /**
     * 插入新评论
     */
    public Long insert(CommentVO commentVO) {
        User user = authenticationService.getLoginUser();
        if(commentVO.getUserId() == null
                ||!commentVO.getUserId().equals(user.getId())){
            Asserts.fail("非法操作：用户id不匹配");
        }
        // 抹去敏感信息
        Comment insert = commentVO.toInsertEntity();

        if (iCommentService.save(insert)) {
            // 更新用户评论数
            User CommentUser = iUserService.selectByIdAndBuildCache(commentVO.getUserId());
            CommentUser.setPostCount(CommentUser.getPostCount() + 1);
            iUserService.updateAndDeleteCache(user);

            return commentVO.getId();
        }
        return null;
    }

    /**
     * 更新评论
     */
    public Long update(CommentVO commentVO) {
        if (commentVO.getId() == null
                ||!iCommentService.exists(new QueryWrapper<Comment>().eq("id",commentVO.getId()))){
            Asserts.fail("评论不存在");
        }
        User user = authenticationService.getLoginUser();
        if(commentVO.getUserId() == null
                ||!commentVO.getUserId().equals(user.getId())){
            Asserts.fail("非法操作：用户id不匹配");
        }
        // 抹去敏感信息
        Comment update = commentVO.toUpdateEntity();
        boolean success = iCommentService.updateAndDeleteCache(update);
        if (success) {
            return update.getId();
        }
        return null;
    }

    /**
     * 逻辑删除
     */
    public Long delete(Long commentId) {
        if (commentId ==null
                ||!iCommentService.exists(new QueryWrapper<Comment>().eq("id",commentId))){
            Asserts.fail("评论不存在");
        }
        Comment comment = iCommentService.selectByIdAndBuildCache(commentId);
        User user = authenticationService.getLoginUser();
        if(!comment.getUserId().equals(user.getId())){
            Asserts.fail("非法操作：用户id不匹配");
        }
        // 逻辑删除
        comment.setStatus(Status.invalid);
        boolean success  = iCommentService.updateAndDeleteCache(comment);
        if (success) {
            // 更新用户评论数
            User Commentuser = iUserService.selectByIdAndBuildCache(comment.getUserId());
            Commentuser.setPostCount(Commentuser.getPostCount() - 1);
            iUserService.updateAndDeleteCache(user);
            // 删除缓存
            return comment.getId();
        }
        return null;
    }


}




